package cn.itcast.client;

import cn.itcast.message.*;
import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class ChatClient {
    public static void main(String[] args) {
        extracted();
    }

    private static void extracted() {
        int writerIdleTimeSeconds = 30;
        NioEventLoopGroup group = new NioEventLoopGroup();
        //netty提供的日志处理器
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        //自定义的消息编码解码器，结合ProtocolFrameDecoder使用
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        //等待登录结果
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        //标记登录结果
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        //标记是否已经退出
        AtomicBoolean EXIT = new AtomicBoolean(false);
        //记录登录消息返回次数
        AtomicInteger LOGIN_RES_COUNT = new AtomicInteger(0);
        Scanner scanner = new Scanner(System.in);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(group);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(LOGGING_HANDLER);
                    pipeline.addLast(new ProtocolFrameDecoder());
                    pipeline.addLast(MESSAGE_CODEC);
                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长,10s 内如果没有向服务器写数据，会触发一个 IdleState#WRITER_IDLE 事件
                    pipeline.addLast(new IdleStateHandler(0, writerIdleTimeSeconds, 0));
                    pipeline.addLast(new ChannelDuplexHandler() { // ChannelDuplexHandler 可以同时作为入站和出站处理器
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了写空闲事件 IdleState.WRITER_IDLE
                            if (event.state() == IdleState.WRITER_IDLE) {
                                log.debug(writerIdleTimeSeconds + "s 没有写数据了，发送一个心跳包");
                                ctx.writeAndFlush(new PingMessage());
                            }
                        }
                    });
                    pipeline.addLast("client handler", new ChannelInboundHandlerAdapter() {
                        // 接收响应消息
                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            log.debug("[接收msg]: {}", msg);
                            if ((msg instanceof LoginResponseMessage)) {
                                LoginResponseMessage response = (LoginResponseMessage) msg;
                                int andIncrement = LOGIN_RES_COUNT.getAndIncrement();
                                if (andIncrement == 0) { //首次收到登录结果，则设置登录结果，并唤醒 system in 线程
                                    if (response.isSuccess()) {
                                        // 如果登录成功
                                        LOGIN.set(true);
                                    }
                                    //登录结果返回， 则唤醒 system in 线程
                                    WAIT_FOR_LOGIN.countDown();
                                } else {
                                    //非首次收到登录结果，且登录失败，并关闭channel
                                    if (!response.isSuccess()) {
                                        System.out.println(response.getReason() + "...即将关闭channel");
                                        ctx.channel().close();
                                    }
                                }
                            }
                        }

                        // 在连接建立后触发 active 事件
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) {
                            // 负责接收用户在控制台的输入，负责向服务器发送各种消息
                            new Thread(() -> {
                                System.out.println("请输入用户名:");
                                String username = scanner.nextLine();
                                if (EXIT.get()) {
                                    return;
                                }
                                System.out.println("请输入密码:");
                                String password = scanner.nextLine();
                                if (EXIT.get()) {
                                    return;
                                }
                                // 构建并发送登录消息
                                LoginRequestMessage message = new LoginRequestMessage(username, password);
                                ctx.writeAndFlush(message);
                                System.out.println("等待后续操作...");
                                try {
                                    //当前线程阻塞，等待登录结果
                                    WAIT_FOR_LOGIN.await();
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                // 如果登录失败
                                if (!LOGIN.get()) {
                                    System.out.println("登录失败...即将关闭channel");
                                    ctx.channel().close();
                                    return;
                                }
                                while (true) {
                                    printM();
                                    String command = null;
                                    try {
                                        command = scanner.nextLine();
                                    } catch (Exception e) {
                                        break;
                                    }
                                    if (EXIT.get()) {
                                        return;
                                    }
                                    String[] commandArray = command.split(" ");
                                    switch (commandArray[0]) {
                                        case "send":
                                            ctx.writeAndFlush(new ChatRequestMessage(username, commandArray[1], commandArray[2]));
                                            break;
                                        case "gsend":
                                            ctx.writeAndFlush(new GroupChatRequestMessage(username, commandArray[1], commandArray[2]));
                                            break;
                                        case "gcreate":
                                            Set<String> set = new HashSet<>(Arrays.asList(commandArray[2].split(",")));
                                            set.add(username); // 加入自己
                                            ctx.writeAndFlush(new GroupCreateRequestMessage(commandArray[1], set));
                                            break;
                                        case "gmembers":
                                            ctx.writeAndFlush(new GroupMembersRequestMessage(commandArray[1]));
                                            break;
                                        case "gjoin":
                                            ctx.writeAndFlush(new GroupJoinRequestMessage(username, commandArray[1]));
                                            break;
                                        case "gquit":
                                            ctx.writeAndFlush(new GroupQuitRequestMessage(username, commandArray[1]));
                                            break;
                                        case "quit":
                                            ctx.channel().close();
                                            return;
                                    }
                                }
                            }, "system in").start();
                        }

                        // 在连接断开时触发
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("连接已经断开，按任意键退出..");
                            EXIT.set(true);
                        }

                        // 在出现异常时触发
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("连接已经断开，按任意键退出..{}", cause.getMessage());
                            EXIT.set(true);
                        }
                    });
                }
            });
            Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
            channel.closeFuture().sync();
        } catch (Exception e) {
            log.error("client error", e);
        } finally {
            group.shutdownGracefully();
        }
    }


    private static void printM() {
        System.out.println("==================================");
        System.out.println("send [username] [content]");
        System.out.println("gsend [group name] [content]");
        System.out.println("gcreate [group name] [m1,m2,m3...]");
        System.out.println("gmembers [group name]");
        System.out.println("gjoin [group name]");
        System.out.println("gquit [group name]");
        System.out.println("quit");
        System.out.println("==================================");
    }

    private static void writeAndFlushMsg(String command, String username, ChannelHandlerContext ctx) {
        String[] s = command.split(" ");
        switch (s[0]) {
            case "send":
                ctx.writeAndFlush(new ChatRequestMessage(username, s[1], s[2]));
                break;
            case "gsend":
                ctx.writeAndFlush(new GroupChatRequestMessage(username, s[1], s[2]));
                break;
            case "gcreate":
                Set<String> set = new HashSet<>(Arrays.asList(s[2].split(",")));
                set.add(username); // 加入自己
                ctx.writeAndFlush(new GroupCreateRequestMessage(s[1], set));
                break;
            case "gmembers":
                ctx.writeAndFlush(new GroupMembersRequestMessage(s[1]));
                break;
            case "gjoin":
                ctx.writeAndFlush(new GroupJoinRequestMessage(username, s[1]));
                break;
            case "gquit":
                ctx.writeAndFlush(new GroupQuitRequestMessage(username, s[1]));
                break;
            case "quit":
                ctx.channel().close();
                return;
        }
    }
}


